const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const url = require("url");
const serverObj = http.createServer((req, res) => {
    const urlObj = url.parse(req.url);
    if (urlObj.pathname.includes("/api")) {
        dataHandle(req, res);
    } else {
        staticHandle(req, res);
    }
});
serverObj.listen(3000, () => {
    console.log("服务器开启成功: http://localhost:3000");
});

function dataHandle(req, res) {
    // console.log(req.method);
    if (req.method === "GET") {
        const obj = url.parse(req.url, true).query;
        fn(req, res, obj);
    } else if (req.method === "POST") {
        let str = "";
        req.on("data", (d) => {
            str += d;
        })
        req.on("end", () => {
            const obj = qs.parse(str);
            fn(req, res, obj);
        })
    }
}

function fn(req, res, reqData) {
    console.log(reqData.type);
    switch (reqData.type) {
        case "getBanner": {
            getBanner(req, res, reqData);
            break;
        }
        case "getGoods": {
            getGoods(req, res, reqData);
            break;
        }
        case "getGoods2": {
            getGoods2(req, res, reqData);
            break;
        }
        case "Goods": {
            Goods(req, res, reqData);
            break;
        }
        case "getThisGood": {
            getThisGood(req, res, reqData);
            break;
        }
        case "register":
            register(req, res, reqData);
            break;
        case "login":
            login(req, res, reqData);
            break;
        case "resetPassword":
            resetPassword(req, res, reqData);
            break;
    }
}
// 获取轮播图
function getBanner(req, res, reqData) {
    fs.readFile("./database/indexBanner.json", (err, data) => {
        if (err) {
            res.write("not data")
        } else {
            res.write(data)
        }
        res.end();
    });
}
// 获取商品1
function getGoods(req, res, reqData) {
    fs.readFile("./database/indexGoods.json", (err, data) => {
        if (err) {
            res.write("not data")
        } else {
            res.write(data)
        }
        res.end();
    });
}
// 获取商品2
function getGoods2(req, res, reqData) {
    fs.readFile("./database/indexGoods2.json", (err, data) => {
        if (err) {
            res.write("not data")
        } else {
            res.write(data)
        }
        res.end();
    });
}
// 获取商品
function Goods(req, res, reqData) {
    fs.readFile("./database/Goods.json", (err, data) => {
        if (err) {
            res.write("not data")
        } else {
            res.write(data)
        }
        res.end();
    });
}
// 获取当前点击的商品
function getThisGood(req, res, reqData) {
    fs.readFile("./database/indexGoods.json", (err, data) => {
        if (err) {
            res.write("not data");
        } else {
            res.write(data);
        }
        res.end();
    });
}
// 登陆
function login(req, res, reqData) {
    fs.readFile("./database/users.json", "utf-8", (err, data) => {
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        let i = 0;
        const flag = userMsg.some((val, idx) => {
            i = idx;
            return val.username === reqData.username;
        })
        if (flag) {
            if (userMsg[i].password === reqData.password) {
                obj.code = 1;
                obj.title = "登录成功";
                obj.data = userMsg[i].username;
            } else {
                obj.code = 2;
                obj.title = "登录失败，密码不符";
                obj.data = "NOTDATA";
            }
        } else {
            obj.code = 0;
            obj.title = "登录失败，用户名不存在";
            obj.data = "NOTDATA";
        }
        res.write(JSON.stringify(obj));
        res.end();
    })
}
// 注册
function register(req, res, reqData) {
    fs.readFile("./database/users.json", "utf-8", (err, data) => {
        // 处理了对应文件不存在的清空和文件内没有数据的清空
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        if (userMsg.some(val => val.username === reqData.username)) {
            obj.code = 0;
            obj.title = "注册失败，用户名重复";
            obj.data = "NOTDATA";
            res.write(JSON.stringify(obj));
            res.end();
        } else {
            userMsg.push({
                username: reqData.username,
                password: reqData.password
            })
            fs.writeFile("./database/users.json", JSON.stringify(userMsg), err => {
                obj.code = 1;
                obj.title = "注册成功";
                obj.data = "NOTDATA";
                res.write(JSON.stringify(obj));
                res.end();
            })
        }
    })
}
// 修改密码
function resetPassword(req, res, reqData) {
    fs.readFile("./database/users.json", "utf-8", (err, data) => {
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        // 备份原数据
        const userMsgOld = err ? [] : (data ? JSON.parse(data) : []);
        let i = 0;
        // 先找用户名
        const flag = userMsg.some((val, idx) => {
            i = idx;
            return val.username === reqData.username;
        })
        // 用户存在
        if (flag) {
            // 判断原来密码
            if (userMsg[i].password === reqData.password1) {
                // 原来的密码修改为传过来的密码
                userMsg.splice(i, 1, {
                    username: reqData.username,
                    password: reqData.password2
                })
                // 写数据
                fs.writeFile("./database/users.json", JSON.stringify(userMsg), err => {
                    obj.code = 1;
                    obj.title = "修改成功";
                    obj.data = "NOTDATA";
                    res.write(JSON.stringify(obj));
                    res.end();
                });
            } else {
                obj.code = 2;
                obj.title = "修改失败，密码不符";
                obj.data = "NOTDATA";
                res.write(JSON.stringify(obj));
                res.end();
            }
        } 

    })
}


// 处理静态资源
function staticHandle(req, res) {
    const urlObj = url.parse(req.url);
    fs.readFile("./dist" + urlObj.pathname, (err, data) => {
        if (err) {
            res.write("notFound");
        } else {
            res.write(data);
        }
        res.end();
    });
}